package zj.com.fragments;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.drawee.view.SimpleDraweeView;

import org.xutils.DbManager;

import java.util.ArrayList;
import java.util.List;

import zj.com.activities.SettingActivity;
import zj.com.db.DBUtil;
import zj.com.model.Dic;
import zj.com.model.InspectItem;
import zj.com.model.UserInfo;
import zj.com.model.Zy;
import zj.com.net.NetManager;
import zj.com.net.OnResponseListener;
import zj.com.util.Constants;
import zj.com.util.DialogUtil;
import zj.com.util.LogUtils;
import zj.com.util.SharedPreferencesUtil;
import zj.com.zj.R;

/**
 * Created by xi on 16/6/3.
 */
//现场检查
public class GrzxFragment extends Fragment implements View.OnClickListener{
    public TextView name_tv,id_tv,sync_tv,set_tv,bm_tv,xm_tv,me_code_tv,prj_code_tv;
    public ImageView  id_tab_line_iv;

    public SimpleDraweeView head_icon,code_iv;
    public int screenWidth;
    public Intent intent;
    public  UserInfo uinfo;


    public ProgressDialog dialog,dialog2;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        DisplayMetrics dpMetrics = new DisplayMetrics();
        getActivity().getWindow().getWindowManager().getDefaultDisplay()
                .getMetrics(dpMetrics);
        screenWidth = dpMetrics.widthPixels;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_grzx, container, false);
        initView(view);

        return view;
    }

    public void initView(View view){

        name_tv = (TextView) view.findViewById(R.id.name_tv);
        id_tv = (TextView) view.findViewById(R.id.id_tv);
        sync_tv = (TextView) view.findViewById(R.id.sync_tv);
        sync_tv.setOnClickListener(this);
        set_tv = (TextView) view.findViewById(R.id.set_tv);
        set_tv.setOnClickListener(this);
        xm_tv = (TextView) view.findViewById(R.id.xm_tv);
        bm_tv = (TextView) view.findViewById(R.id.bm_tv);
        prj_code_tv= (TextView) view.findViewById(R.id.prj_code_tv);
        me_code_tv= (TextView) view.findViewById(R.id.me_code_tv);
        me_code_tv.setOnClickListener(this);
        prj_code_tv.setOnClickListener(this);

        id_tab_line_iv = (ImageView) view.findViewById(R.id.id_tab_line_iv);
        code_iv= (SimpleDraweeView) view.findViewById(R.id.code_iv);
        head_icon = (SimpleDraweeView) view.findViewById(R.id.head_icon);

        Object obj = SharedPreferencesUtil.readObject(getActivity(), "user");
        if(obj != null){

             uinfo =(UserInfo)obj;
            initValue(uinfo);
        }else{
            initData();
        }

    }

    public void initData(){
        dialog2 = DialogUtil.createProgressDialog(getActivity(),"提示","获取数据中..");
        NetManager.getInstance(getActivity()).doGetUserInfo(new OnResponseListener<UserInfo>() {
            @Override
            public void onComplete(boolean isOK, UserInfo result, int errorCode, String errorMsg) {

                if(isOK){

                    uinfo = result;
                    initValue(result);
                    dialog2.dismiss();

                }else{
                    Toast.makeText(getActivity(), errorMsg, Toast.LENGTH_SHORT).show();
                    dialog2.dismiss();

                }


            }

            @Override
            public void onInternError(int errorCode, String errorMessage) {
                dialog2.dismiss();
                Toast.makeText(getActivity(), errorMessage, Toast.LENGTH_SHORT).show();
            }
        });
    }

    public void initValue(UserInfo uinfo){

        name_tv.setText("姓名： "+uinfo.getUserName());
        id_tv.setText("编号：" + uinfo.getUserUid());
        bm_tv.setText(uinfo.getOrgFullName());
        if(uinfo.getProjectName() != null && uinfo.getProjectName().equals("null") ){
            xm_tv.setText("");

        }else{
            xm_tv.setText(uinfo.getProjectName());
        }
        head_icon.setImageURI(Uri.parse(uinfo.getUserImageUrl()));
        code_iv.setImageURI(Uri.parse(uinfo.getUserQRCodeUrl()));
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }

    @Override
    public void onStart() {
        super.onStart();
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onDetach() {
        super.onDetach();
    }

    @Override
    public void onClick(View v) {
        RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) id_tab_line_iv
                .getLayoutParams();
        switch (v.getId()){

            case R.id.set_tv:
                intent = new Intent(getActivity(), SettingActivity.class);
                startActivity(intent);
                break;
            case R.id.me_code_tv:
                me_code_tv.setTextColor(Color.parseColor("#6799ff"));
                prj_code_tv.setTextColor(Color.parseColor("#a4a4a4"));
                lp.leftMargin =0;
                code_iv.setImageURI(Uri.parse(uinfo.getUserQRCodeUrl()));

                break;
            case R.id.prj_code_tv:
                lp.leftMargin =
                        screenWidth / 2;

                if(uinfo != null && uinfo.getProjectQRCodeUrl() != null){
                    code_iv.setImageURI(Uri.parse(uinfo.getProjectQRCodeUrl()));
                }


                prj_code_tv.setTextColor(Color.parseColor("#6799ff"));
                me_code_tv.setTextColor(Color.parseColor("#a4a4a4"));
                break;
            case R.id.sync_tv:
                sync();
                break;
        }
        id_tab_line_iv.setLayoutParams(lp);

    }

    public int totalCount = 0;
    public int count = 0;

    public void sync(){

        DbManager dbManager = DBUtil.getInstance(getActivity()).getDBManager();
        try{
            dbManager.delete(Dic.class);
            dialog = DialogUtil.createProgressDialog(getActivity(),"提示","同步数据中...");
            List<String> list = new ArrayList<String>();
            list.add(Constants.InspectType);
            list.add(Constants.UserLevel);
            list.add(Constants.AttachType);
            list.add(Constants.InspectionState);
            list.add(Constants.RiskType);
            list.add(Constants.RiskLevel);
            list.add(Constants.RepairRecordState);
            list.add(Constants.ProjectState);
            list.add(Constants.OrgLevel);
            list.add(Constants.AuditState);

            totalCount = list.size();


            for(String str:list){

                NetManager.getInstance(getActivity()).obtainDic(str, new OnResponseListener<List<Dic>>() {
                    @Override
                    public void onComplete(boolean isOK, List<Dic> result, int errorCode, String errorMsg) {

                        if(isOK){
                            count++;
                            if(totalCount == count){
                                count = 0;
                                obtainZy();
                            }
                        }else{
                            dialog.dismiss();

                        }

                    }

                    @Override
                    public void onInternError(int errorCode, String errorMessage) {
                        dialog.dismiss();

                        Toast.makeText(getActivity(), "同步失败", Toast.LENGTH_SHORT).show();
                    }
                });
            }

        }catch(Exception e){
            dialog.dismiss();
            Toast.makeText(getActivity(), "同步失败", Toast.LENGTH_SHORT).show();

        }

    }

    public void obtainZy(){


        try{
            DbManager dbManager = DBUtil.getInstance(getActivity()).getDBManager();
            dbManager.delete(Zy.class);
            dbManager.delete(InspectItem.class);
        }catch(Exception e){

        }


        NetManager.getInstance(getActivity()).obtainZy(new OnResponseListener<List<Zy>>() {
            @Override
            public void onComplete(boolean isOK, List<Zy> result, int errorCode, String errorMsg) {

                if(isOK){
                    if(result != null && result.size() > 0){
                        int count = 0;
                        int totoalCount = result.size();
                        for(Zy zy:result){
                            count ++;
                            obtainInpectItem(zy);
                        }

                        if(totoalCount == count){
                            Toast.makeText(getActivity(),"同步成功",Toast.LENGTH_SHORT).show();
                            dialog.dismiss();
                        }


                    }else{
                        dialog.dismiss();
                    }


                }else{
                    dialog.dismiss();
                    Toast.makeText(getActivity(),"获取失败",Toast.LENGTH_SHORT).show();

                }


            }

            @Override
            public void onInternError(int errorCode, String errorMessage) {
                dialog.dismiss();
                Toast.makeText(getActivity(),"获取失败",Toast.LENGTH_SHORT).show();
            }
        });
    }

    public void obtainInpectItem(Zy zy){


        NetManager.getInstance(getActivity()).obtainInspectItemList(zy, new OnResponseListener<List<InspectItem>>() {
            @Override
            public void onComplete(boolean isOK, List<InspectItem> result, int errorCode, String errorMsg) {

                if (isOK) {

                } else {

                }
            }

            @Override
            public void onInternError(int errorCode, String errorMessage) {
                dialog.dismiss();
            }
        });
    }

}
